﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Truextend.CoffeShop.Model;

namespace Truextend.CoffeShop.DataAccess
{
    public class DetailDataAccess
    {
        static CoffeShopEntities db = new CoffeShopEntities();

        public static void AddDetail(int productId)
        {
            Detail detail = new Detail();
            Product product = new Product();
            try {

                product = (from p in db.Product where p.ProductId == productId select p).First();

                detail.ProductReference.EntityKey = product.EntityKey;
                db.AddToDetail(detail);
                db.SaveChanges();

            }catch(Exception){}

        }

        public static Detail GetLastDetail() {

            Detail detail = new Detail();

            try {
                detail = (from p in db.Detail orderby p.DetailId descending select p).First();
            }
            catch (Exception) { }

            return detail;

        }

        public static List<Detail> GetAllDetailsOfAnOrder(int orderId) {

            List<Detail> listDetails = new List<Detail>();

            try {

                listDetails = (from p in db.Detail.Include("Product") where p.Order.OrderId == orderId select p).ToList();
            
            }catch (Exception) {}

            return listDetails;
        }

        public static void AddListDetails(List<Detail> listDetails) { 
            
            try{
                foreach(var detail in listDetails){
                    db.AddToDetail(detail);
                }

                db.SaveChanges();

            }catch(Exception){}
            
        }

        public static Detail GetDetailById(int detailId)
        {

            Detail detail = new Detail();

            try
            {
                detail = (from p in db.Detail where p.DetailId == detailId select p).First();
            }
            catch (Exception) { }

            return detail;
        }
    }
}
